package com.chujian.Utils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.LruCache;
import android.widget.ImageView;
/**
 * 实现从网络上获取并加载图片的功能
 * @author 周映凯
 *
 */
public class ImageLoader {
	private LruCache<String, Bitmap> mCaches;

	public ImageLoader() {

		int maxMemory = (int) Runtime.getRuntime().maxMemory();
		int cacheSize = maxMemory / 4;
		mCaches = new LruCache<String, Bitmap>(cacheSize) {
			@Override
			protected int sizeOf(String key, Bitmap value) {
				// TODO Auto-generated method stub
				return value.getByteCount();
			}
		};
	}

	public void addBitmapToCache(String url, Bitmap bitmap) {
		// TODO Auto-generated method stub
		if (getBitmapFromCache(url) == null) {
			mCaches.put(url, bitmap);
		}
	}

	public Bitmap getBitmapFromCache(String url) {
		// TODO Auto-generated method stub
		return mCaches.get(url);
	}

	private class FoodAsyncTask extends AsyncTask<String, Void, Bitmap> {
		private String mUrl;
		private ImageView mImageView;

		public FoodAsyncTask(String mUrl, ImageView mImageView) {
			super();
			this.mUrl = mUrl;
			this.mImageView = mImageView;
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			// TODO Auto-generated method stub
			String url = params[0];// get url
			Bitmap bitmap = getBitmapFromURL(url);
			if (bitmap != null) {
				addBitmapToCache(url, bitmap);
			}
			return bitmap;
		}

		@Override
		protected void onPostExecute(Bitmap bitmap) {
			// TODO Auto-generated method stub
			super.onPostExecute(bitmap);
			if (mImageView != null && bitmap != null) {
				mImageView.setImageBitmap(bitmap);
			}
		}

	}

	public void showImageByAsyncTask(ImageView imageView, String url) {
		Bitmap bitmap = getBitmapFromCache(url);
		if (bitmap == null) {
			new FoodAsyncTask(url, imageView).execute(url);
		} else {
			imageView.setImageBitmap(bitmap);
		}
	}

	/**
	 * 根据url获取Bitmap对象
	 * 
	 * @param urlstring
	 * @return
	 */
	public Bitmap getBitmapFromURL(String urlstring) {
		// TODO Auto-generated method stub
		Bitmap bitmap;
		// InputStream is=null;
		try {
			URL url = new URL(urlstring);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			InputStream is = new BufferedInputStream(conn.getInputStream());
			bitmap = BitmapFactory.decodeStream(is);
			conn.disconnect();
			is.close();
			return bitmap;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

}
